package cn.school.common.message;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 微信消息发送
 */
@Service
public class WechatMessageSendUtil {

    private  String appid_web;
    private  String app_secret_web;

    public void sendWxNotice(String openId, String tempId, List<WxMaTemplateData> templateDataList,String page){
        JsonParser JSON_PARSER = new JsonParser();
        //1,配置小程序信息
        WxMaInMemoryConfig wxConfig = new WxMaInMemoryConfig();
        wxConfig.setAppid(appid_web);//小程序appid
        wxConfig.setSecret(app_secret_web);//小程序AppSecret

        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(wxConfig);



        //3，设置推送消息
        WxMaTemplateMessage templateMessage = WxMaTemplateMessage.builder()
                .toUser(openId)//要推送的用户openid
                .formId(System.currentTimeMillis()+"")//收集到的formid
                .templateId(tempId)//推送的模版id（在小程序后台设置）
                .data(templateDataList)//模版信息
                .page(page)//要跳转到小程序那个页面
                .build();
        //4，发起推送
        try {
            String responseContent = wxMaService.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send", templateMessage.toJson());
            JsonObject jsonObject = JSON_PARSER.parse(responseContent).getAsJsonObject();
            if (jsonObject.get(WxMaConstants.ERRCODE).getAsInt() != 0) {
                throw new WxErrorException(WxError.fromJson(responseContent));
            }
        } catch (WxErrorException e) {
            System.out.println("推送失败：" + e.getMessage());
        }
    }

}
